<template>
    <div class="detail-box">
        <van-nav-bar title="订单详情" left-text="返回" left-arrow @click-left="onClickLeft" />

        <van-collapse v-model="activeNames" :accordion="true">
			<van-collapse-item name="1">
				<template slot="title">
					订单信息
				</template>
				<template slot="value">
					查看详情
				</template>
				<template slot="default">
                    <viewOrderTemplate :dataResouce="pageDefaultList" :pageDataList="defaultLabelList"></viewOrderTemplate>
                    <!-- 内容审核文件 -->
                    <div class="auditFile">
                        <van-cell :border="false">
                            <template slot="icon">
                                <span class="custom-title" style="width: 170px">内容审核文件：</span>
                                <div style="width: 100%">
                                    <van-uploader 
                                        v-if="downloadStatus.includes(details.status)" 
                                        :after-read="afterRead" :accept="'doc/docx'" 
                                        :max-count="5" multiple>
                                        <template slot="default">
                                            <van-button type="primary" size="mini">上传文件</van-button>
                                        </template>
                                    </van-uploader>
                                    <div v-else>
                                        <a v-for="file in details.review_file && details.review_file.indexOf('&') ? details.review_file.split('&') : details.review_file" :key="file"
                                            :href="`${baseUrls}/api/download?path=${file}`">
                                            <van-icon name="orders-o" size="22px" color="#2d8cf0"/>
                                        </a>
                                    </div>
                                </div>
                            </template>
                        </van-cell>
                    </div>
				</template>
			</van-collapse-item>
            <van-collapse-item name="2">
				<template slot="title">
					流程进度
				</template>
				<template slot="value">
					查看详情
				</template>
				<template slot="default">
                    <van-steps direction="vertical" :active="0">
                        <van-step v-for="status in details.statuss" :key="status.id">
                            <h3>{{status.pivot.created_at}}</h3>
                            {{ status.name }}
                            <p v-if="status.name.includes(['内审文件撰写中'])">代理人：{{details.agent.name}} 接单 </p>
                            <p v-if="status.name.includes(['发明人提交成功,等待分配代理人'])">发明人：{{details.liaisons}} 提交成功</p>
                        </van-step>
                    </van-steps>
				</template>
			</van-collapse-item>
            <van-collapse-item name="3">
				<template slot="title">
					审批意见
				</template>
				<template slot="value">
					查看详情
				</template>
				<template slot="default">
                    <div v-if="details.opinions && details.opinions.length>0">
                        <van-steps direction="vertical" :active="0">
                            <van-step v-for="opinion in details.opinions" :key="opinion.id">
                                <h3>{{opinion.created_at}}</h3>
                                <p>{{ opinion.review_user }} {{opinion.review}}</p>
                            </van-step>
                        </van-steps>
                    </div>
                    <div v-else style="min-height: 80px; line-height: 80px; text-align: center;">
                        暂无审批意见
                    </div>
				</template>
			</van-collapse-item>
		</van-collapse>
        
        <!-- <van-tabs v-model="activeName" animated>
            <van-tab title="订单信息" name="订单信息">
                <viewOrderTemplate :dataResouce="pageDefaultList" :pageDataList="defaultLabelList"></viewOrderTemplate>

                <div class="auditFile">
                    <van-cell :border="false">
                        <template slot="icon">
                            <span class="custom-title" style="margin-right: 15px; width: 170px">内容审核文件：</span>
                            <div style="width: 100%">
                                <van-uploader 
                                    v-if="downloadStatus.includes(details.status)" 
                                    :after-read="afterRead" :accept="'doc/docx'" 
                                    :max-count="5" multiple>
                                    <template slot="default">
                                        <van-button type="primary" size="mini">上传文件</van-button>
                                    </template>
                                </van-uploader>
                                <a v-for="file in details.review_file && details.review_file.indexOf('&') ? details.review_file.split('&') : details.review_file" :key="file"
                                    :href="`${baseUrls}/api/download?path=${file}`">
                                    <van-icon name="orders-o" size="22px" color="#2d8cf0"/>
                                </a>
                            </div>
                        </template>
                    </van-cell>
                </div>
            </van-tab>
            <van-tab title="流程进度" name="流程进度">
                <van-steps direction="vertical" :active="0">
                    <van-step v-for="status in details.statuss" :key="status.id">
                        <h3>提交时间：{{status.created_at}}</h3>
                        {{ status.name }}
                        <p v-if="status.name.includes(['内审文件撰写中'])">代理人：{{details.agent.name}} 接单 </p>
                        <p v-if="status.name.includes(['发明人提交成功,等待分配代理人'])">发明人：{{details.liaisons}} 提交成功</p>
                    </van-step>
                </van-steps>
            </van-tab>
            <van-tab title="审批意见" name="审批意见">
                <div v-if="details.opinions" style="min-height: 80px; line-height: 80px; text-align: center;">
                    暂无审批意见
                </div>
                <div v-else>
                    <van-steps direction="vertical" :active="0">
                        <van-step v-for="opinion in details.opinions" :key="opinion.id">
                            <h3>{{opinion.created_at}}</h3>
                            {{ status.name }}
                            <p>{{ opinion.review_user }}</p>>
                        </van-step>
                    </van-steps>
                </div>
            </van-tab>
        </van-tabs> -->

        <!-- <van-dialog
            v-model="showFile"
            title="消息"
            show-cancel-button
            >
            <p v-html="message"></p>
        </van-dialog> -->
    </div>
</template>

<script>
import { Dialog, Toast } from 'vant'
import { uploader } from '~/util/upLoad'
import { downLoadFiles } from '~/util/downLoad'
import axios from 'axios'
import { getUserInfo, getCurrentOrderList } from '~/api/commonApi'
import viewOrderTemplate from '~/components/_viewOrder'

export default {
    data() {
        return {
            activeNames: '1',
            details: [],
            activeName: '订单信息',
            pageDefaultList: [],
            tabActive: 0,
            isShowDialog: true,
            userInfo: [],
            showFile: false,
            message: `
                <div style="font-size: 14px;text-align: left;white-space: pre-line;padding: 0 20px;color: #323233">
                    <p style="text-indent: 2em;margin: 0">请直接上传已完成的word文档,单个主体文件,无需分解,仅供内容 审查</p>
                    * 如果双报或者分案等,请分别上传word文件
                    * 文件命名格式: 订单编号-代理人姓名-案件名称-案件类型.doc/docx
                    * 多文件格式为：订单编号-序号(数字)-代理人姓名-案件名称-案件类型.doc/docx
                </div>
            `,
            downloadStatus: ['代理人撰写中', '案件修改中'],
            
            defaultLabelList: [
					'专利名称', '专利类型', '订单编号', '订单状态', '联络人', '联络人邮箱', '流程人员',
					'联络人电话', '技术领域', '技术背景', '技术问题', '技术方案', '项目优势', '具体实施方式', '附图', '附件'
				],
            filesLabelList: ['附图', '附件'],
            baseUrls: global.baseurl
        }
    },
    //缓存也会走的钩子
    deactivated(){
        this.$destroy(true);//销毁组件
    },
    activated() {
        let id = this.$route.params.id
        getCurrentOrderList(this.$axios, id).then(res => {
            if(res.status === 200) {
                this.details = res.data.data
                this.pageDefaultList = [
                    { label: '专利名称', value: this.details.patent_name },
                    { label: '专利类型', value: this.details.type },
                    { label: '订单状态', value: this.details.status },
                    { label: '订单编号', value: this.details.order_number },
                    { label: '联络人', value: this.details.liaisons },
                    { label: '流程人员', value: this.details.process ? this.details.process.name : '' },
                    { label: '联络人邮箱', value: this.details.liaisons_email },
                    { label: '联络人电话', value: this.details.liaisons_tel },
                    { label: '技术领域', value: this.details.territory },
                    { label: '技术背景', value: this.details.background },
                    { label: '技术问题', value: this.details.problem },
                    { label: '技术方案', value: this.details.plan },
                    { label: '项目优势', value: this.details.advantage },
                    { label: '具体实施方式', value: this.details.way },
                    { label: '附图', value: this.details.img },
                    { label: '附件', value: this.details.file }
                ]
            }
        })
    },
    methods: {
        onClickLeft() {
            this.$router.go(-1);
        },
        onSelFiles(){
            this.isShowDialog = true
            Dialog.alert({
                title: '注意',
                message: this.message,
            }).then(() => {
                
            });
        },
        afterRead(file) {
            // 此时可以自行将文件上传至服务器
            // console.log(file)

            // 获取文件名称信息
            let fileName = []

            const formData = new FormData()

            if(file.length) {
                // 多文件上传
                file.map((item, i) => {
                    fileName.push(item.file.name)
                    if(i === 0) {
                        formData.append('file', item.file)
                    }else{
                        formData.append(`file${i}`, item.file)
                    }
                })
            }else{
                fileName.push(file.file.name)
                // 单文件上传
                formData.append("file", file.file)
            }

            // order id
            let order = this.details.id

            // 效验文件名称
            let flag = false
            
            if(this.details.status === '代理人撰写中') {
                flag = fileName.every(item =>{
                    let nameList = item.split('.')[0].split('-')
                    // 当状态为代理人撰写中时  正确文件名字格式（x-x-xxxxxxxxxxxxx-xx）
                    return item.split('.')[0].match(/^[\d]-([A-Z]{1}-){2}[\d]{13}(-[\u4e00-\u9fa5]+)*$/) &&
                    `${nameList[0]}-${nameList[1]}-${nameList[2]}-${nameList[3]}` === this.details.order_number &&
                    `${nameList[4]}` === this.details.agent.name
                })
            }else{
                flag = fileName.every(item =>{
                    let nameList = item.split('.')[0].split('-')
                    // 当状态不为代理人撰写中时  正确文件名字格式（x-x-xxxxxxxxxxxxx-xx(Rx)）
                    if(nameList[3].indexOf('(')) {
                        return item.split('.')[0].match(/^[\d]-([A-Z]{1}-){2}[\d]{13}([(][-\d]*[)])?(-[\u4e00-\u9fa5]+)*([(][R]{1}[\d]*[)]){1}$/) &&
                        `${nameList[0]}-${nameList[1]}-${nameList[2]}-${nameList[3].split('(')[0]}` === this.details.order_number &&
                        `${nameList[4]}` === this.details.agent.name
                    }
                    return item.split('.')[0].match(/^[\d]-([A-Z]{1}-){2}[\d]{13}([(][-\d]*[)])?(-[\u4e00-\u9fa5]+)*([(][R]{1}[\d]*[)]){1}$/) &&
                    `${nameList[0]}-${nameList[1]}-${nameList[2]}-${nameList[3]}` === this.details.order_number &&
                    `${nameList[4]}` === this.details.agent.name
                })
            }

            if(flag) {
                axios.post(`http://192.168.124.118/api/order/${order}/upload`, formData, {
                    headers: {
                        "context-type": "multer/form-data",
                        Authorization: "Bearer " + this.$cookies.get('token')
                    }
                }).then(res => {
                    // console.log(res)
                    if(res.status === 200) {
                        Toast('上传成功')
                        // 上传成功后重新刷新页面信息
                        getCurrentOrderList(this.$axios, this.details.id).then(res => {
                            if(res.status === 200) {
                                this.details = res.data.data
                            }
                        })    
                    }else{
                        Toast('上传错误')
                    }
                })
            }else{
                Toast('上传文件格式不正确，请重新上传')
            }

        }
    },
    components: {
        viewOrderTemplate
    }
}
</script>

<style lang="less" scoped>
    .detail-box{

        /deep/ .van-collapse-item__content{
			padding: 0;
		}

		/deep/ .van-cell__right-icon{
			display: none;
		}

        .style{
            font-size: 14px !important;
            text-align: left !important;
            white-space: pre-line !important;
        }

        .van-field__label{
            width: 100px;
        }

        .context{
            padding: 20px;
            text-align: center;
        }

        .van-step__title{
            h3,
            h4,
            p{
                margin: 0;
            }
            
            h3{
                margin-bottom: 40px;
                font-size: 30px;
            }

            h4,p{
                margin: 10px;
                font-size: 14px;
                font-weight: 500;
            }
        }

        .file-Dialog{
            padding: 30px 0 0 0;
 
            p{
                margin: 0;
                padding: 0;
            }
            
            .title,
            .waring,
            .tip{
                font-size: 14px;
                padding: 5px;
            }

            .waring{
                color: red;
            }

        }

        .van-card{
            background-color: #fff;
        }

    }
</style>